import Router from '../../utils/router';
import base from '../../config/base.js';
import service from '../../services/cutprice.js';
import Record_server from '../../services/record-stat.js';
import ext from '../../utils/login';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    icon_play: base.static + 'store/play2.png',
    icon_free: base.static + 'bargain/cutprice4.png',
    icon_myFree: base.static + 'bargain/myCut1.png',
    icon_next: base.static + 'collage/next.png',
    icon_mask_sellout: base.static + 'collage/out.png',
    icon_fail: base.static + 'bargain/cut-fail.png',
    icon_noorder: base.static + '/collage/no-order-list.png',
    icon_no_avater: base.static + '/free/head.png',
    store_id: '',
    user_info: '',
    current: 1, //当前选项卡
    canTake: null, //可以领取弹窗
    canTakeTimes: 1,
    goodsList: [], //免费拿
    endFreeBloon: true,
    loadFreeBloon: true,
    pageFree: '',
    orderlist: [], //我的免费拿
    endOrderBloon: true,
    loadOrderBloon: true,
    pageOrder: '',
    nomoreFree: true,
    nomoreOrder: true,
    swiperList: '', //免费拿轮播
    clickTimes: 1, //我的免费拿点击次数
    hottodyList: [], // 2.12.0今日热销
    pageHot: 0,
    endHotBloon: true,
    loadHotBloon: true,
    clickBloon: true, //检查商品状态事件节流
    info_authorize: '', //授权状态
    show_authorize: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let user_info = wx.getStorageSync('user_info') || {id:'',lastView:{seid:''}};
    that.setData({
      store_id: user_info.lastView.seid,
      user_id: user_info.id,
      info_authorize: user_info.info_authorize,
    })
   
    if (options.method && options.method == 'navigateBack') {
    } else {
      that.getCutPrice(1);
      that.swiperCollage();
    }

  },
  //授权
  onGotUserInfo: function (e) {
    let that = this;
    let d = e.detail;
    if (d.errMsg == 'getUserInfo:ok') {
      ext.getUserInfo(d, b => {
        if (b) {
          that.setData({
            show_authorize: false,
            info_authorize: 1,
          })
        }
      });
    }
  }, 
  // 免费拿轮播
  swiperCollage: function () {
    let that = this;
    let params = {}
    service.getCycleMsg(params, function (res) {
      if (res.code && res.code == 200) {
        that.setData({
          swiperList: res.data.dataList
        })
      }
    });
    wx.stopPullDownRefresh()
  },
  // 今日热销列表
  storeListHot: function (page) {
    let that = this;
    let params = {
      page: page,
      per_page: 10
    }
    service.customerRecommend(params, function (res) {
      if (res && res.code == 200) {
        let stolistHot = that.data.hottodyList.concat(res.data.recommend);
        that.setData({
          hottodyList: stolistHot,
          pageHot: page + 1,
          endHotBloon: true
        });
        //是否到底
        if (stolistHot.length == res.data.count) {
          that.setData({
            loadHotBloon: false,
            nomoreFree: false,
          })
        }
      }
      wx.stopPullDownRefresh();
    });
  },
  //砍价列表
  getCutPrice: function (page) {
    let that = this;
    let params = {
      page: page,
      offset: 10
    }
    service.getBargainList(params, function (res) {
      if (res.code && res.code == 1) {
        let stolist = that.data.goodsList.concat(res.data.data);
        that.setData({
          goodsList: stolist,
          pageFree: page + 1,
          canTake: res.data.name,
          endFreeBloon: true
        })
        if (stolist.length >= res.data.count) {
          that.setData({
            loadFreeBloon: false,
          })
          that.storeListHot(1)
        }
      }
    });
    wx.stopPullDownRefresh()
  },
  //我的砍价列表
  priceOrderList(page) {
    let that = this;
    let params = {
      page: page,
      offset: 10
    }
    service.BargainUser(params, function (res) {
      if (res && res.code == 1) {
        let orderlist = that.data.orderlist.concat(res.data.list);
        // 结束时间
        if (orderlist != ""){
          let myDate = new Date();
          let hours = 23 - myDate.getHours()
          orderlist.forEach((item, index) => {
            let second = ''
            if (item.order_status == 1 && item.time) {//待分享
              let floor1 = hours * 3600;
              let floor2 = (hours + 24) * 3600
              let time = item.time;
              let strArr = item.end_time.split("-");
              if (time <= floor1) {
                item.time_str = '今日' + strArr[2].split(' ')[1];
              } else if (floor1 < time && time < floor2) {
                item.time_str = '明日' + strArr[2].split(' ')[1];
              } else if (time > floor2) {
                item.time_str = strArr[1] + '月' + strArr[2].split(' ')[0] + '日' + strArr[2].split(' ')[1];
              }
            }
          })
        }
        that.setData({
          orderlist: orderlist,
          pageOrder: page + 1,
          endOrderBloon: true,
        })
        if (orderlist.length > 0 && orderlist.length >= res.data.count) {
          that.setData({
            nomoreOrder: false,
            loadOrderBloon: false,
          })
        }
      }
      wx.stopPullDownRefresh()
    })
  },
  // 检查状态
  checkStatus: function(e){
    let that = this;
    // 判断授权
    if (that.data.info_authorize !=1){
      that.setData({
        show_authorize: true,
      })
      return
    }
    // 库存
    if (e.currentTarget.dataset.storagenum == 0) {
      return
    }
    // 事件截流
    if (!that.data.clickBloon) {
      return
    }
    
    that.data.clickBloon = false
    let bngsid = e.currentTarget.dataset.bngsid;
    let inx = e.currentTarget.dataset.inx;
    let difference = e.currentTarget.dataset.difference;
    let params = {
      bngsid: bngsid
    }
    service.bargainCheck(params, function (resStr) {
      if (resStr && resStr.code == 1) {
        that.initBargainOrder(inx)
      } else if (resStr.code == 0){
        switch (resStr.data.order_status){
          case '1': wx.showModal({
                    content: '该商品正在砍价中，\r\n快去邀请好友砍价吧',
                      confirmText: '查看详情',
                      confirmColor: '#FE3F3E',
                      success(res) {
                        if (res.confirm) {
                          Router.go('bargaindetail', `store_id=${resStr.data.bslnid}&bnorid=${resStr.data.bnorid}`)
                        }
                      }
                    })
                    break;
          case '2': wx.showModal({
                      content: '该订单尚未支付，砍价优惠即将失效，快去支付吧',
                      confirmText: '去支付',
                      confirmColor: '#FE3F3E',
                      success(res) {
                        if (res.confirm) {
                          Router.go('orderDetail', `orid=${resStr.data.orid}`);
                        }
                      }
                    })
                    break;
          case '3': wx.showModal({
                      content: '恭喜您！该商品已砍价成功，快去领取吧',
                      confirmText: '立即领取',
                      confirmColor: '#FE3F3E',
                      success(res) {
                        if (res.confirm) {
                          Router.go('jielong', `bnorid=${resStr.data.bnorid}&bngsid=${bngsid}&types=2&difference=${resStr.data.total_money}`);
                        }
                      }
                    })
                    break;
                   
        }
      }
      that.data.clickBloon = true
    })
  },
  // 立即使用
  useBtn: function () {
    let that = this;
    that.setData({
      canTake: null,
      icon_free: base.static + 'bargain/cutprice3.png',
      icon_myFree: base.static + 'bargain/myCut2.png',
      current: 2,
      canTakeTimes: 2,
      clickTimes: 2,
    })
    that.priceOrderList(1)
  },
  // 点击底部选项卡
  chooseTab: function (e) {
    let that = this;
    let current = e.currentTarget.dataset.curt;
    if (current == 1) {
      that.setData({
        icon_free: base.static + 'bargain/cutprice4.png',
        icon_myFree: base.static + 'bargain/myCut1.png',
        current: current,
      })
    } else {
      if (that.data.orderlist == "" && current != that.data.current) {
        that.priceOrderList(1)
      }
      that.setData({
        icon_free: base.static + 'bargain/cutprice3.png',
        icon_myFree: base.static + 'bargain/myCut2.png',
        current: current,
      })
    }
  },
  //阻止swipeer手滑
  stopTouchMove: function () {
    return false
  },
  // 去首页
  goStore: function () {
    Router.go('store', ``)
  },
  // 去规则
  goWeb: function () {
    let url = encodeURIComponent('https://kpxd.zhengdianhaohuo.com/h5/#/active/win3_931')
    Router.go('web', `url=${url}`)
  },
  //去订单详情
  goorders(e) {
    let orid = e.currentTarget.dataset.orid
    Router.go('orderDetail', `orid=${orid}`);
  },
  //去砍价详情
  goBargainDetail: function (e) {
    let that = this;
    Router.go("bargaindetail", `store_id=${e.currentTarget.dataset.bslnid}&bnorid=${e.currentTarget.dataset.bnorid}`);
  },
  // 发起创建订单
  initBargainOrder: function(inx){
    let that = this;
    let goodsList = that.data.goodsList;
    let store_id = that.data.store_id;
    let params = {
      bngsid: goodsList[inx].bngsid,
      goods_pic: goodsList[inx].is_main,
      goods_title: goodsList[inx].name,
      bslnid: store_id,
      goods_list_money: goodsList[inx].starting_price,
    }
    service.init_bargain_order(params, function (resStr) {
      if (resStr && resStr.code == 1) {
        Router.go("bargaindetail", `store_id=${store_id}&bnorid=${resStr.data.bnorid}`);
      }
    })
  },
  hideMask: function(){
    this.setData({
      canTake: null,
      canTakeTimes: 2,
    })
  },
  //去创建订单页面
  gosubaddress(e) {
    let bnorid = e.currentTarget.dataset.bnorid;
    let difference = e.currentTarget.dataset.difference;
    let bngsid = e.currentTarget.dataset.bngsid;
    Router.go('jielong', `bnorid=${bnorid}&bngsid=${bngsid}&types=2&difference=${difference}`);
  },
  queryMultipleNodes(scroll) {
    let that = this;
    if (that.data.goodsList == "") {
      return
    }
    let query = wx.createSelectorQuery().in(that);
    let scrolls = 0;
    let index = 0;
    let s = wx.getSystemInfoSync().windowHeight;
    query.selectAll('.test').boundingClientRect(function (rects) {
      if (scrolls < scroll) {
        for (let i = index, len = rects.length; i < len; i++) {
          let rect = rects[i];
          if (rect && 0 < rect.top && rect.bottom < s) {
            that.viewRecord(rect.id, "view")
            index = i;
            scrolls = scroll
          }
        }
      } else {
        for (let i = index; i >= 0; i--) {
          let rect = rects[i];
          if (rect && 0 < rect.top && rect.bottom < s) {
            index = i;
            scrolls = scroll
          }
        }
      }
    }).exec()
  },
  //滚动和点击屏幕记录
  viewRecord: function (goodsid, act) {
    let that = this;
    let params = {
      name: "ltxx_buyer",
      page: 'cut_price_list',
      position: 'cut_price_list',
      productid: goodsid,
      userid: that.data.user_id,
      storeid: that.data.store_id,
      act: act,
      env: getApp().globalData.env
    }
    Record_server.recordstat(params, function () { });
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    if (that.data.current == 1) {
      that.scrollTimer = setTimeout(() => {
        that.setData({
          scrolltop: e.scrollTop
        })
        that.queryMultipleNodes(e.scrollTop)
      }, 500);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
  onPullDownRefresh: function () {
    let that = this;
    if (that.data.current == 1) {
      that.setData({
        goodsList: [], //免费拿
        endFreeBloon: false,
        loadFreeBloon: true,
        nomoreFree: true,
        hottodyList: [], // 2.12.0今日热销
        endHotBloon: true,
        loadHotBloon: true,
      })
      that.getCutPrice(1);
      that.swiperCollage();
    } else {
      that.setData({
        orderlist: [], //我的免费拿
        endOrderBloon: false,
        loadOrderBloon: true,
        pageOrder: '',
        nomoreOrder: true,
      });
      that.priceOrderList(1)
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    if (that.data.current == 1 && that.data.loadFreeBloon && that.data.endFreeBloon) { //免费拿列表
      that.setData({
        endFreeBloon: false
      })
      that.getCutPrice(that.data.pageFree);
    } else if (that.data.current == 1 && that.data.loadHotBloon && that.data.endHotBloon) {//今日热销
      that.setData({
        endHotBloon: false
      })
      that.storeListHot(that.data.pageHot);
    } else if (that.data.current == 2 && that.data.loadOrderBloon && that.data.endOrderBloon) {//我的免费拿
      that.setData({
        endOrderBloon: false
      })
      that.priceOrderList(that.data.pageOrder);
    }
  },
})